package org.gos.mission.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.gos.mission.domain.Mission;
import org.gos.mission.domain.User;
import org.gos.mission.util.DB;


public class MissionDaoMySQLImpl {

	public void add(Connection conn,Mission mission) {
		String sql = "insert into t_mission values(null,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement pStmt = null;
		try {
			pStmt = DB.prepare(conn, sql);
			pStmt.setString(1, mission.getTitle());
			pStmt.setTimestamp(2, new Timestamp(mission.getStartTime().getTime()));
			pStmt.setTimestamp(3, new Timestamp(mission.getEndTime().getTime()));
			pStmt.setInt(4, mission.getUser().getId());
			pStmt.setString(5, mission.getContent());
			pStmt.setTimestamp(6, mission.getMissionStartTime() == null?null:new Timestamp(mission.getMissionStartTime().getTime()));
			pStmt.setTimestamp(7, mission.getMissionEndTime()==null?null:new Timestamp(mission.getMissionEndTime().getTime()));
			pStmt.setString(8, mission.getCompleted());
			pStmt.setString(9, mission.getRecruiting());
			pStmt.setInt(10, mission.getPeopleRecruit());
			pStmt.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DB.close(pStmt);
		}
	}

	public List<Mission> getMissionsByUser(Connection conn, User user) {
		List<Mission> missions = new ArrayList<Mission>();
		String sql = "select *  from t_mission order by start_time desc";
		Statement stmt = DB.getStatement(conn);
		ResultSet rs = DB.getResultSet(stmt, sql);
		try {
			while(rs.next()){
				Mission mission = new Mission();
				mission.setId(rs.getInt(1));
				mission.setTitle(rs.getString(2));
				mission.setStartTime(rs.getTimestamp(3));
				mission.setEndTime(rs.getTimestamp(4));
				mission.setUser(user);
				mission.setContent(rs.getString(6));
				mission.setMissionStartTime(rs.getTimestamp(7));
				mission.setMissionEndTime(rs.getTimestamp(8));
				mission.setCompleted(rs.getString(9));
				mission.setRecruiting(rs.getString(10));
				mission.setPeopleRecruit(rs.getInt(11));
				missions.add(mission);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally{
			DB.close(rs);
			DB.close(stmt);
		}
		return missions;
	}

	
}
